package com.markerhub.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markerhub.application.service.SmsService;
import com.markerhub.common.enums.HealthcodeStateEnums;
import com.markerhub.entity.TDeviceData;
import com.markerhub.entity.TUnusualPerson;
import com.markerhub.entity.TWarnPhone;
import com.markerhub.mapper.TDeviceDataMapper;
import com.markerhub.service.ITDeviceDataService;
import com.markerhub.service.ITUnusualPersonService;
import com.markerhub.service.ITWarnPhoneService;
import com.markerhub.utils.ReadFileUtil;
import com.markerhub.vo.SmsParam;
import com.markerhub.vo.response.PersonInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 上报数据表 服务实现类
 * </p>
 *
 * @author zhz
 * @since 2021-09-18
 */
@Service
public class TDeviceDataServiceImpl extends ServiceImpl<TDeviceDataMapper, TDeviceData> implements ITDeviceDataService {

    @Autowired
    private TDeviceDataMapper deviceDataMapper;

    @Autowired
    private ITUnusualPersonService itUnusualPersonService;

    @Autowired
    private ITWarnPhoneService itWarnPhoneService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ITDeviceDataService deviceDataService;

    @Override
    public void signHandle(Long id) {
        TDeviceData deviceData = deviceDataMapper.selectById(id);
        if (null != deviceData) {
            //新增异常人信息
            TUnusualPerson tUnusualPerson = new TUnusualPerson();
            tUnusualPerson.setImsi(deviceData.getImsi());
            tUnusualPerson.setSmsType(deviceData.getSmsType());
            tUnusualPerson.setCreateTime(LocalDateTime.now());
            itUnusualPersonService.save(tUnusualPerson);

            //查询预警短信列表
            List<TWarnPhone> list = itWarnPhoneService.list();
            if (CollectionUtil.isNotEmpty(list)) {
                for (TWarnPhone tWarnPhone : list) {
                    //发送短信
                    smsService.sendSms(new SmsParam(tWarnPhone.getWarnPhone(), deviceData.getImsi()));
                }
            }

        }

    }

    @Override
    public List<TDeviceData> queryNewestDataList(int size) {
        LambdaQueryWrapper<TDeviceData> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(TDeviceData::getDeviceUpTime);
        wrapper.last("limit " + size);
        List<TDeviceData> deviceDatas = baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(deviceDatas)) {
            return Collections.EMPTY_LIST;
        }
        //去重
        List<TDeviceData> deviceDataList = deviceDatas.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TDeviceData::getImsi))), ArrayList::new));
        //排序（降序）
        deviceDataList.sort(Comparator.comparing(TDeviceData::getDeviceUpTime).reversed());
        return deviceDataList;
    }

    //@Override
    //@Scheduled(cron = "0 */1 * * * ?")
/*    public List<PersonInfoVO> ShowDate() {
        ArrayList<String> fileData = ReadFileUtil.getFileData();
        if (CollectionUtil.isNotEmpty(fileData)) {
            ArrayList<TDeviceData> tDeviceDataList = new ArrayList<>();
            for (String fileDatum : fileData) {
                try {
                    String[] split = fileDatum.split(",");
                    String imsi = split[2];
                    String deviceUpTime = split[4];
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = format.parse(deviceUpTime);
                    TDeviceData tDeviceData = new TDeviceData();
                    tDeviceData.setImsi(imsi);
                    tDeviceData.setDeviceUpTime(date);
                    System.out.println("上报数据" + tDeviceData);
                    tDeviceDataList.add(tDeviceData);
                } catch (Exception e) {

                }
            }
            //保存设备上报数据
            deviceDataService.saveBatch(tDeviceDataList);

            Set<String> imsis = tDeviceDataList.stream().map(TDeviceData::getImsi).collect(Collectors.toSet());

            List<TUnusualPerson> personList = itUnusualPersonService.selectByImsis(imsis);
*//**            if(CollectionUtil.isEmpty(personList)){
                System.out.println("从远程库获取到空数据...");
                return CollectionUtil.newArrayList();
            }*//*
            Map<String, TUnusualPerson> imsiMap = personList.stream()
                    .collect(Collectors.toMap(TUnusualPerson::getImsi, Function.identity(), (k1, k2) -> k1));
            List<PersonInfoVO> list = CollectionUtil.newArrayList();
            //所有都查不到，作为无法识别全部返回
            if (CollectionUtil.isEmpty(personList)) {
                for (String imsi : imsis) {
                    PersonInfoVO personInfoVO = new PersonInfoVO();
                    personInfoVO.setImsi(imsi.replaceAll("(\\d{5})\\d{5}(\\d{5})", "$1****$2"));
                    personInfoVO.setHealthcodeState(HealthcodeStateEnums.NO.getCode());
                    list.add(personInfoVO);
                }
                System.out.println("返回所有都识别不到的");
                return list;
            }
            for (String imsi : imsis) {
                PersonInfoVO personInfoVO = new PersonInfoVO();
                personInfoVO.setImsi(imsi);
                TUnusualPerson tUnusualPerson = imsiMap.get(imsi);
                if (ObjectUtil.isNotNull(tUnusualPerson)) {
                    //红码，发送短信
                    if (HealthcodeStateEnums.RED.getCode().equals(tUnusualPerson.getHealthcodeState())) {
                        sendSms(personInfoVO);
                    }
                    //黄码，发送短信
                    if (HealthcodeStateEnums.YELLOW.getCode().equals(tUnusualPerson.getHealthcodeState())) {
                        sendSms(personInfoVO);
                    }
                    personInfoVO.setAcidtestResult(tUnusualPerson.getAcidtestResult());
                    personInfoVO.setAcidtestTime(
                            tUnusualPerson.getAcidtestTime() == null ? null :
                                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(tUnusualPerson.getAcidtestTime()));
                    personInfoVO.setCardId(tUnusualPerson.getCardId());
                    personInfoVO.setHealthcodeState(tUnusualPerson.getHealthcodeState());
                    personInfoVO.setHodometer(tUnusualPerson.getHodometer());
                    personInfoVO.setName(tUnusualPerson.getName());
                    personInfoVO.setVaccination(tUnusualPerson.getVaccination());
                    personInfoVO.setMobile(tUnusualPerson.getMobile());
                } else {
                    //无法识别imsi,发送短信
                    sendSms(personInfoVO);
                    personInfoVO.setHealthcodeState(HealthcodeStateEnums.NO.getCode());

                }
                list.add(personInfoVO);
            }

            System.out.println(list.toString());
            //灵瞳码脱敏
            if (CollectionUtil.isNotEmpty(list)) {
                for (PersonInfoVO personInfoVO : list) {
                    personInfoVO.setImsi(personInfoVO.getImsi() == null ? null : personInfoVO.getImsi().replaceAll("(\\d{5})\\d{5}(\\d{5})", "$1****$2"));
                }
            }
            //返回数据给前端展示
            System.out.println("返回至少有一个识别到的数据" + list);
            return list;
        }
        System.out.println("读取不到文件数据，返回空数据");
        return CollectionUtil.newArrayList();
    }*/

    public List<PersonInfoVO> ShowDate(){
        List<TUnusualPerson> tUnusualPersonList = itUnusualPersonService.selectAll();
        if (CollectionUtil.isNotEmpty(tUnusualPersonList)) {
            List<PersonInfoVO> list = CollectionUtil.newArrayList();
            for (TUnusualPerson tUnusualPerson : tUnusualPersonList) {
                PersonInfoVO personInfoVO = new PersonInfoVO();
                personInfoVO.setImsi(tUnusualPerson.getImsi());
                personInfoVO.setAcidtestResult(tUnusualPerson.getAcidtestResult());
                personInfoVO.setAcidtestTime(
                        tUnusualPerson.getAcidtestTime() == null ? null :
                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(tUnusualPerson.getAcidtestTime()));
                personInfoVO.setCardId(tUnusualPerson.getCardId());
                personInfoVO.setHealthcodeState(tUnusualPerson.getHealthcodeState());
                personInfoVO.setHodometer(tUnusualPerson.getHodometer());
                personInfoVO.setName(tUnusualPerson.getName());
                personInfoVO.setVaccination(tUnusualPerson.getVaccination());
                personInfoVO.setMobile(tUnusualPerson.getMobile());
                list.add(personInfoVO);
            }
            //灵瞳码脱敏
            if (CollectionUtil.isNotEmpty(list)) {
                for (PersonInfoVO personInfoVO : list) {
                    personInfoVO.setImsi(personInfoVO.getImsi() == null ? null : personInfoVO.getImsi().replaceAll("(\\d{5})\\d{5}(\\d{5})", "$1****$2"));
                }
            }
            Collections.shuffle(list);
            return list;
        }
        return CollectionUtil.newArrayList();
    }

    public void sendSms(PersonInfoVO personInfoVO) {
        List<TWarnPhone> warnPhonelist = itWarnPhoneService.list();
        if (CollectionUtil.isNotEmpty(warnPhonelist)) {
            for (TWarnPhone tWarnPhone : warnPhonelist) {
                smsService.sendSms(new SmsParam(tWarnPhone.getWarnPhone(), personInfoVO.getImsi()));
            }
        }
    }
}
